//------------------游戏控制--------------------//
// 游戏时钟(定时器)
var gameTimer;
// 生成子弹(定时器)
var createBulletTimer;
// 生成敌人(定时器)
var createEnemyTimer;
//---------------------------------------------//
//------------------游戏资源--------------------//
// 子弹数组
var bulletArr = [];
// 子弹对象池
var bulletPoolArr = [];
// 敌人数组
var enemyArr = [];
// 敌人对象池
var enemyPoolArr = [];
//---------------------------------------------//
$(function () {
    // 初始化飞机位置
    $(myPlaneDom).css({
        left: $(window).width() / 2 - $(myPlaneDom).width() / 2 + 'px',
        top: $(window).height() - $(myPlaneDom).height() - 100 + 'px'
    })
    // 自动开始游戏
    // startBtn.click();
    // 开始游戏
    $(startBtn).click(() => {
        $(startBtn).hide();
        $('body').css('background-image', 'url(../img/start-bg.png)');
        // 隐藏菜单
        $(panelDom).addClass('hide');
        // 玩家移动
        planeMove()
        // 生成子弹
        createBulletTimer = setInterval(createBullet, 1000 / createBulletSpeed);
        createEnemyTimer = setInterval(createEnemy, 1000 / createEnemySpeed);
        // 发射子弹
        gameTimer = setInterval(() => {
            // 子弹移动
            moveObjects(bulletArr, bulletPoolArr, ballDom, -bulletMoveSpeed);
            // 敌人移动
            moveObjects(enemyArr, enemyPoolArr, enemyDom, enemyMoveSpeed);
            checkDomCollision(bulletArr, 'bullet');
            checkDomCollision();
        }, 15)
    })
})
function init(){
    $(ballDom).empty();
    $(enemyDom).empty();
    bulletArr = [];
    enemyArr = [];
    $(myPlaneDom).css({
        left: $(window).width() / 2 - $(myPlaneDom).width() / 2 + 'px',
        top: $(window).height() - $(myPlaneDom).height() - 100 + 'px'
    })
    $(startBtn).click();
}
// 玩家移动实现
function planeMove() {
    // 触摸屏幕(移动端)
    $(document).on('touchstart', function (e) {
        // 触摸开始时的坐标
        var startX = e.originalEvent.touches[0].clientX;
        var startY = e.originalEvent.touches[0].clientY;
        // 飞机开始时的坐标 
        var planeStartX = parseInt($(myPlaneDom).css('left'));
        var planeStartY = parseInt($(myPlaneDom).css('top'));
        $(document).on('touchmove', function (e) {
            var moveX = e.originalEvent.touches[0].clientX;
            var moveY = e.originalEvent.touches[0].clientY;
            $(myPlaneDom).css({
                'left': planeStartX + moveX - startX + 'px',
                'top': planeStartY + moveY - startY + 'px'
            });
        });
    }).on('touchend', function () {
        $(document).off('touchmove');
        $(document).off('touchstart');
    });
    // 鼠标按下(PC端)
    $(document).on('mousedown', function (e1) {
        // 鼠标按下瞬间的坐标
        var oldX = e1.clientX;
        var oldY = e1.clientY;
        // 鼠标按下瞬间，飞机的旧坐标
        var oldPlaneX = parseInt($(myPlaneDom).css("left"));
        var oldPlaneY = parseInt($(myPlaneDom).css("top"));
        $(document).mousemove(function (e2) {
            var newX = e2.clientX;
            var newY = e2.clientY;
            $(myPlaneDom).css({
                left: oldPlaneX + newX - oldX + 'px',
                top: oldPlaneY + newY - oldY + 'px'
            });
        });

    }).on('mouseup', function () {
        // 鼠标抬起
        $(document).off('mousemove');
    });
}
// 生成对象封装
function createObject(type, poolArr, container, objArr) {
    let object = null;
    if (poolArr.length) {
        object = poolArr.pop();
    } else {
        var enemyType = Math.random() * 10;
        if (enemyType < 8) {
            enemyType = 1;
        } else {
            enemyType = 2;
        }
        object = document.createElement('img');
        object.src = type === 'bullet' ? './img/bullet.png' : `./img/enemy${enemyType}.png`;
        $(object).attr('type', enemyType);
        object.classList.add('pf');
    }
    if (type === 'bullet') {
        // 初始化子弹位置
        object.style.left = myPlaneDom.offsetLeft + myPlaneDom.offsetWidth / 2 - 3 + 'px';
        object.style.top = myPlaneDom.offsetTop + myPlaneDom.offsetHeight / 2 - 7 + 'px';
    } else {
        // 初始化敌人位置
        object.style.left = Math.random() * (document.documentElement.clientWidth - 50) + 'px';
        object.style.top = - object.offsetHeight + 'px';
    }
    if (type === 'enemy') {
        thisType = $(object).attr('type');
        $(object).attr('hp', thisType == 1 ? 2 : 4).attr('score', thisType == 1 ? 500 : 1000);
    } else {
        $(object).attr('damage', 1);
    }
    container.appendChild(object);
    objArr.push(object);
}
// 调用
function createBullet() {
    createObject('bullet', bulletPoolArr, ballDom, bulletArr);
}
function createEnemy() {
    createObject('enemy', enemyPoolArr, enemyDom, enemyArr);
}
// 移动对象封装
function moveObjects(objects, objectPool, container, speed) {
    for (let i = 0; i < objects.length; i++) {
        let object = objects[i];
        let goal = object.offsetTop + speed;
        if (speed < 0 ? goal + 16 <= 0 : goal >= document.documentElement.clientHeight) {
            // 移出屏幕
            container.removeChild(object);
            objectPool.push(object);
            objects.splice(i, 1);
            i--;
        } else {
            // 更新位置
            object.style.top = goal + 'px';
        }
    }
}
// 碰撞检测实现
function isCollision(dom1, dom2) {
    // 没碰着的情况
    if (
        dom1.offsetLeft + dom1.offsetWidth < dom2.offsetLeft ||
        dom1.offsetLeft > dom2.offsetLeft + dom2.offsetWidth ||
        dom1.offsetTop + dom1.offsetHeight < dom2.offsetTop ||
        dom1.offsetTop > dom2.offsetTop + dom2.offsetHeight
    ) {
        return false;
    }
    return true;
}
// 游戏碰撞实现
function checkDomCollision(thisDomArr = [myPlaneDom], type = 'player') {
    for (var i = 0; i < enemyArr.length; i++) {
        var enemy = enemyArr[i];;
        for (var j = 0; j < thisDomArr.length; j++) {
            if (type == 'bullet') {
                var bullet = thisDomArr[j];
                if (isCollision(enemy, bullet)) {
                    // 碰撞成功
                    // 移除子弹
                    if ($(enemy).attr('hp') <= 0) {
                        // 移除敌机
                        enemyArr.splice(i, 1);
                        i--;
                        enemyDom.removeChild(enemy);
                        enemyPoolArr.push(enemy);
                        score1Dom.innerText = +score1Dom.innerText + +$(enemy).attr('score');
                    } else {
                        $(enemy).attr('hp', (+$(enemy).attr('hp')) - +$(bullet).attr('damage'));
                    }
                    thisDomArr.splice(j, 1);
                    ballDom.removeChild(bullet);
                    bulletPoolArr.push(bullet);
                }
            } else {
                if (isCollision(enemy, myPlaneDom)) {
                    gameOver();
                }
            }

        }
    }
}
// 游戏结束
function gameOver() {
    var score =  $('#score1Dom').text();
    clearInterval(gameTimer);
    clearInterval(createBulletTimer);
    clearInterval(createEnemyTimer);
    document.onmousemove=null;
    document.onmousedown=null;
    document.ontouchmove=null;
    document.ontouchstart=null;
    
    layer.open({
        type: 1,
        area: ['70%', '20%'], // 宽高
        title: "飞机大战得分", // 不显示标题栏
        skin: 'class-layer-demo-custom',
        btn: ['重新开始'],
        closeBtn: 0,
        btn1: function () {
            $('#score1Dom').text('0');
            layer.closeAll();
            init();
        },
        content: `<div style="width:100%;height:100%;display:flex;align-items: center;justify-content: center;">
        <p style="font-size: 26px; font-weight:bold; text-align:center;">${score}分</p>
    </div>`
    });
}